import {
	ENV_URL
} from '@/utils/env.js'

// UTF-8 解码函数
function utf8ArrayToStr(array) {
	let out = '';
	let i = 0;
	while (i < array.length) {
		let c = array[i++];
		switch (c >> 4) {
			case 0:
			case 1:
			case 2:
			case 3:
			case 4:
			case 5:
			case 6:
			case 7:
				// 0xxxxxxx
				out += String.fromCharCode(c);
				break;
			case 12:
			case 13:
				// 110x xxxx   10xx xxxx
				let char2 = array[i++];
				out += String.fromCharCode(((c & 0x1F) << 6) | (char2 & 0x3F));
				break;
			case 14:
				// 1110 xxxx  10xx xxxx  10xx xxxx
				char2 = array[i++];
				let char3 = array[i++];
				out += String.fromCharCode(((c & 0x0F) << 12) |
					((char2 & 0x3F) << 6) |
					((char3 & 0x3F) << 0));
				break;
		}
	}
	return out;
}

export function formatDataFromSSE(chunk) {
	return chunk
		.split("data:")
		.filter((item) => item)
		.map((item) => {
			try {
				const jsonData = JSON.parse(item);
				return jsonData.choices[0]?.delta?.content;
			} catch (err) {
				return "";
			}
		})
		.join("");
}

export async function connectSSE(url, body, onMessage, onError, onComplete) {
	let isAborted = false;

	try {
		const token = uni.getStorageSync('token');
		const baseURL = ENV_URL() || "";

		// 使用uni.request发送请求
		const requestTask = uni.request({
			url: baseURL + url,
			method: "POST",
			header: {
				"Accept": "text/event-stream",
				"Authorization": token ? "Bearer " + token : ""
			},
			data: body,
			enableChunked: true,
			responseType: 'arraybuffer',
			timeout: 60000, // 60秒超时
			success: (res) => {
				onComplete()
				console.log('SSE响应:', res);
			},
			fail: (err) => {
				if (isAborted) return;
				console.error('SSE请求失败:', err);
				onError?.(err);
			},

		});

		requestTask.onChunkReceived((res) => {
			if (isAborted) return;

			console.log('SSE分块数据:', res);

			// 处理分块数据
			if (res.data) {
				let responseData = res.data;
				// 使用UTF-8解码函数处理中文
				responseData = utf8ArrayToStr(responseData);
				console.log('转换后的SSE数据:', responseData);
				// 处理转换后的字符串数据
				if (typeof responseData === 'string') {
					console.log('转换后的SSE数据:', responseData);
					const data = formatDataFromSSE(responseData);
					if (data) {
						console.log('转换后数据:', data);
						onMessage(data);
					}
				}
			}
		})

		// 返回取消函数
		return () => {
			isAborted = true;
			if (requestTask) {
				requestTask.abort();
			}
		};
	} catch (err) {
		console.error('SSE连接异常:', err);
		onError?.(err);
		return () => {};
	}
}